// 计分搜索系统，采用计算分数的方式对整个数据进行排序
// 越重要，分数越高
function countDegree(element, keywords, position, { posDegree = 10 } = {}) {
    keywords = keywords.map((word) =>
        word instanceof RegExp ? word : new RegExp(word, "i")
    );
    let count = 0;
    for (let index = 0; index < position.length; index++) {
        const pos = position[index];
        let total = 0;
        keywords.forEach((word, keywordIndex) => {
            let deg = element[pos].search(word);
            // 搜索文本位置，-1 最不相关，然后是 0 最相关，依次排列
            total += (deg === -1 ? deg : 10 / (deg + 1)) * (keywordIndex + 1);
        });
        count += total * posDegree * (index + 1);
        if (count > 0) break;
    }
    return count;
}
export default function (searchResult, keywords, position) {
    if (!(searchResult instanceof Array)) return searchResult;
    console.time("搜索结果优化中");
    const result = searchResult
        .map((cur, index) => ({
            originIndex: index,
            degree: countDegree(cur, keywords, position),
        }))
        .sort((prev, cur) => cur.degree - prev.degree)
        .map((i) => {
            return searchResult[i.originIndex];
        });
    console.timeEnd("搜索结果优化中");
    return result;
}
